package com.library.common.util;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.library.common.config.SmsConfig;
import com.library.common.constant.Constants;
import lombok.extern.log4j.Log4j2;

/**
 * 阿里云短信发送工具类
 *
 * @author: xyh
 * @create: 2023-09-24
 **/
@Log4j2
public class SmsUtil {

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 必填，AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    /**
     * 发送短信
     *
     * @param phone 手机号码，目前只支持对多单手机号码发送短信
     * @param codeParam 短信模板变量对应的顺序
     */
    public static boolean sendSms(String phone, String codeParam) throws Exception {
        Client client = SmsUtil.createClient(SmsConfig.accessKeyId, SmsConfig.accessKeySecret);
        //组合API发送需要的参数
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                //必填:待发送手机号
                .setPhoneNumbers(phone)
                //必填:短信签名-可在短信控制台中找到
                .setSignName(SmsConfig.signName)
                //必填:短信模板-可在短信控制台中找到
                .setTemplateCode(SmsConfig.templateCode)
                //可选:模板中的变量替换JSON串
                .setTemplateParam("{\"code\":"+codeParam+"}");
        try {
            //通过client发送
            SendSmsResponse smsResponse = client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());
            if(smsResponse.getBody().code.equals(Constants.SMS_SEND_SUCCESS)) {
                log.info("短信发送成功！，手机号：{}", phone);
                return true;
            } else {
                log.error("短信发送失败！，手机号：{}, 错误原因：{}", phone, smsResponse.getBody().message);
                return false;
            }
        } catch (TeaException err) {
            log.error("短信发送异常!，手机号：{}，错误信息：", phone, err);
            throw new RuntimeException(err);
        } catch (Exception e) {
            log.error("短信发送异常!，手机号：{}，错误信息：", phone, e);
            throw new RuntimeException(e);
        }
    }

}
